 <template>
  <div class="order-report-container">

    <!-- 查询条件 -->
    <div class="search-container">

        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="时间范围">
            <el-select v-model="searchForm.timeRange" placeholder="请选择时间范围" class="w-48" @change="handleTimeRangeChange" style="width: 200px;">
              <el-option label="今天" value="today" />
              <el-option label="本周" value="thisWeek" />
              <el-option label="本月" value="thisMonth" />
              <el-option label="本季度" value="thisQuarter" />
              <el-option label="今年" value="thisYear" />
              <el-option label="上周" value="lastWeek" />
              <el-option label="上月" value="lastMonth" />
              <el-option label="上季度" value="lastQuarter" />
              <el-option label="去年" value="lastYear" />
              <el-option label="自定义时间" value="custom" />
            </el-select>
          </el-form-item>
          
          <el-form-item v-if="showDatePicker">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              class="w-80"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="getReportData">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>

    </div>
    
    <!-- 订单状态统计卡片 -->
    <div class="status-cards-container">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card class="status-card">
            <div class="card-content">
              <div class="card-title">订单总数</div>
              <div class="card-value">{{ reportData.orderTotal }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="status-card">
            <div class="card-content">
              <div class="card-title">待出库</div>
              <div class="card-value">{{ reportData.pendingDelivery }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="status-card">
            <div class="card-content">
              <div class="card-title">已出库</div>
              <div class="card-value">{{ reportData.delivered }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="status-card">
            <div class="card-content">
              <div class="card-title">运输中</div>
              <div class="card-value">{{ reportData.inTransit }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="status-card">
            <div class="card-content">
              <div class="card-title">抵达国外仓</div>
              <div class="card-value">{{ reportData.arrivedAbroad }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="status-card">
            <div class="card-content">
              <div class="card-title">配送中</div>
              <div class="card-value">{{ reportData.delivering }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="status-card">
            <div class="card-content">
              <div class="card-title">已签收</div>
              <div class="card-value">{{ reportData.signed }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <!-- 订单状态饼图 -->
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>订单状态分布</span>
              </div>
            </template>
            <div ref="orderStatusChart" class="chart" style="height: 400px;"></div>
          </el-card>
        </el-col>
        
        <!-- 订单趋势图 -->
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>订单数量趋势</span>
              </div>
            </template>
            <div ref="orderTrendChart" class="chart" style="height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup >
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import http from '@/utils/servers'
import moment from 'moment'

// 搜索表单数据
const searchForm = reactive({
  timeRange: 'thisMonth', // 默认本月
  dateRange: []
})

// 是否显示自定义日期选择器
const showDatePicker = ref(false)

// 报表数据
const reportData = reactive({
  orderTotal: 0,
  pendingDelivery: 0,
  delivered: 0,
  inTransit: 0,
  arrivedAbroad: 0,
  delivering: 0,
  signed: 0
})

// 图表实例
let orderStatusChart = null
let orderTrendChart = null
const orderStatusChartRef = ref(null)
const orderTrendChartRef = ref(null)

// 处理时间范围变化
const handleTimeRangeChange = (value) => {
  showDatePicker.value = value === 'custom'
}

// 重置表单
const resetForm = () => {
  searchForm.timeRange = 'thisMonth'
  searchForm.dateRange = []
  showDatePicker.value = false
}

// 获取报表数据
const getReportData = async () => {
  try {
    // 构建请求参数
    const params = {
      timeRange: searchForm.timeRange
    }
    
    // 如果是自定义时间范围，添加日期范围参数
    if (searchForm.timeRange === 'custom' && searchForm.dateRange.length > 0) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    // 这里应该调用实际的API获取数据
    // 由于是示例，这里使用模拟数据
    // const res = await http.get('/api/report/order', { params })
    // reportData = res.data
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    generateMockData()
    
    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('获取报表数据失败:', error)
  }
}

// 生成模拟数据
const generateMockData = () => {
  // 随机生成各状态订单数量
  const orderTotal = Math.floor(Math.random() * 1000) + 500
  const pendingDelivery = Math.floor(Math.random() * 200) + 50
  const delivered = Math.floor(Math.random() * 200) + 50
  const inTransit = Math.floor(Math.random() * 150) + 30
  const arrivedAbroad = Math.floor(Math.random() * 100) + 20
  const delivering = Math.floor(Math.random() * 100) + 20
  const signed = Math.floor(Math.random() * 300) + 100
  
  reportData.orderTotal = orderTotal
  reportData.pendingDelivery = pendingDelivery
  reportData.delivered = delivered
  reportData.inTransit = inTransit
  reportData.arrivedAbroad = arrivedAbroad
  reportData.delivering = delivering
  reportData.signed = signed
}

// 初始化订单状态分布饼图
const initOrderStatusChart = () => {
  if (orderStatusChartRef.value) {
    orderStatusChart = echarts.init(orderStatusChartRef.value)
    console.log('ggggggg')
    orderStatusChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: ['待出库', '已出库', '运输中', '抵达国外仓', '配送中', '已签收']
      },
      series: [
        {
          name: '订单状态',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: []
        }
      ]
    })
  }
}

// 初始化订单趋势图
const initOrderTrendChart = () => {
  if (orderTrendChartRef.value) {
    orderTrendChart = echarts.init(orderTrendChartRef.value)
    orderTrendChart.setOption({
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['订单总数', '新增订单']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: []
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '订单总数',
          type: 'line',
          stack: '总量',
          data: []
        },
        {
          name: '新增订单',
          type: 'line',
          stack: '总量',
          data: []
        }
      ]
    })
  }
}

// 更新图表数据
const updateCharts = () => {
  // 更新订单状态分布饼图
  if (orderStatusChart) {
    const pieData = [
      { value: reportData.pendingDelivery, name: '待出库' },
      { value: reportData.delivered, name: '已出库' },
      { value: reportData.inTransit, name: '运输中' },
      { value: reportData.arrivedAbroad, name: '抵达国外仓' },
      { value: reportData.delivering, name: '配送中' },
      { value: reportData.signed, name: '已签收' }
    ]
        console.log(orderStatusChart,'2222222222')
    orderStatusChart.setOption({
      series: [
        {
          data: pieData
        }
      ]
    })
  }
  
  // 更新订单趋势图
  if (orderTrendChart) {
    // 生成最近30天的日期和模拟数据
    const dates = []
    const totalOrders = []
    const newOrders = []
    
    for (let i = 29; i >= 0; i--) {
      const date = moment().subtract(i, 'days').format('MM-DD')
      dates.push(date)
      
      // 生成模拟数据
      const newOrderCount = Math.floor(Math.random() * 50) + 10
      newOrders.push(newOrderCount)
      
      // 累计订单数
      if (i === 29) {
        totalOrders.push(newOrderCount)
      } else {
        totalOrders.push(totalOrders[totalOrders.length - 1] + newOrderCount)
      }
    }
    
    orderTrendChart.setOption({
      xAxis: {
        data: dates
      },
      series: [
        {
          name: '订单总数',
          data: totalOrders
        },
        {
          name: '新增订单',
          data: newOrders
        }
      ]
    })
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (orderStatusChart) {
    orderStatusChart.resize()
  }
  if (orderTrendChart) {
    orderTrendChart.resize()
  }
}

// 组件挂载时初始化
onMounted(() => {
  initOrderStatusChart()
  initOrderTrendChart()
  getReportData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  if (orderStatusChart) {
    orderStatusChart.dispose()
  }
  if (orderTrendChart) {
    orderTrendChart.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped lang="scss">
.order-report-container {
    padding: 10px;
    background-color: #f5f7fa;

}

.page-header {
  margin-bottom: 20px;
  h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
  }
}

.search-container {
    text-align: left;
  margin-bottom: 20px;
  .search-form {
    margin-bottom: 0;
  }
}

.status-cards-container {
  margin-bottom: 20px;
  .status-card {
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    .card-content {
      text-align: center;
      .card-title {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
      }
      .card-value {
        font-size: 24px;
        font-weight: 600;
        color: #1890ff;
      }
    }
  }
}

.charts-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .chart {
    width: 100%;
  }
}
</style>